/*
 * Copyright 2012 yura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opu.db.obj.vis.domain.dao.impl;

import java.util.ArrayList;
import java.util.List;
import org.opu.db.obj.vis.domain.dao.AttributeDao;
import org.opu.db.obj.vis.domain.dao.ObjectEntryDao;
import org.opu.db.obj.vis.domain.domains.AbstractAttributeEntry;
import org.opu.db.obj.vis.domain.domains.AttributeId;
import org.opu.db.obj.vis.domain.domains.ObjectEntry;

/**
 *
 * @author yura
 */
public class AttributeDaoImpl implements AttributeDao{
    
    private ObjectEntryDao objectEntryDao;

    public AttributeDaoImpl(ObjectEntryDao objectEntryDao) {
        this.objectEntryDao = objectEntryDao;
    }

    @Override
    public AbstractAttributeEntry get(AttributeId id) {
        ObjectEntry get = getObject(id);
        for (AbstractAttributeEntry attributeEntry : get.getAttributes()) {
            if(attributeEntry.getId().equals(id)) {
                return attributeEntry;
            }
        }
        return null;
    }

    @Override
    public List<AbstractAttributeEntry> getList() {
        List<AbstractAttributeEntry> list = new ArrayList<AbstractAttributeEntry>();
        for(ObjectEntry o : objectEntryDao.getList()) {
            for (AbstractAttributeEntry attributeEntry : o.getAttributes()) {
                list.add(attributeEntry);
            }
        }
        return list;
    }

    @Override
    public AttributeId save(AbstractAttributeEntry object) {
        ObjectEntry get = getObject(object.getId());
        ArrayList<AbstractAttributeEntry> attributes = get.getAttributes();
        attributes.remove(object);
        attributes.add(object);
        objectEntryDao.save(get);
        return object.getId();
    }

    @Override
    public void saveAll(List<AbstractAttributeEntry> list) {
        // TODO: Optimization requered here!
        for (AbstractAttributeEntry entry : list) {
            save(entry);
        }
    }

    @Override
    public void saveOrUpdate(AbstractAttributeEntry object) {
        save(object);
    }

    @Override
    public void delete(AbstractAttributeEntry object) {
        ObjectEntry get = getObject(object.getId());
        get.getAttributes().remove(object);
        objectEntryDao.save(get);
    }

    private ObjectEntry getObject(AttributeId id) {
        return objectEntryDao.get(id.getObjectEntry().getId());
    }
    
}
